<link rel="import" href="/bower_components/iron-form/iron-form.html">
<link rel="import" href="/bower_components/iron-pages/iron-pages.html">
<link rel="import" href="/bower_components/paper-button/paper-button.html">
<link rel="import" href="/bower_components/paper-tabs/paper-tabs.html">
<link rel="import" href="/bower_components/paper-tooltip/paper-tooltip.html">
<link rel="import" href="/bower_components/polymer/polymer.html">
<link rel="import" href="/ui/elements/flake_detection/flake-filter.html">
<link rel="import" href="/ui/elements/flake_detection/rank-flake-item.html">


<dom-module id="rank-flakes">
  <template>
    <style>
      table {
        border: 1px solid gray;
      }

      table th {
        padding: 5px;
        color: #FFF;
        white-space: nowrap;
        text-align: left;
      }

      rank-flake-item:nth-child(odd) {
        background-color: #E8F0FE;
      }

      rank-flake-item:nth-child(even) {
        background-color: #FFF;
      }

      rank-flake-item {
        display: table-row;
      }

      .group-header {
        text-align: center;
      }

      .flake-header {
        background-color: #4285F4;
      }

      .bug-header {
        background-color: #669DF6;
      }

      .hidden {
        display: none;
      }

      paper-button {
        color: #fff;
        background: #4285F4;
        margin: 20px;
      }

      #form-div #form-buttons{
        float: left;
        width: 100vw;
      }

      .paging {
        padding: 5px;
      }

      .previous, .next {
        color: #1A73EB;
        background: none;
        border: none;
        padding: 0;
        margin: 0;
        font: inherit;
        border-bottom:1px solid #1A73EB;
        cursor: pointer;
      }

      .disabled {
        color: #9AA0A6;
        background: none;
        border: none;
        padding: 0;
        font: inherit;
        border-bottom:1px solid #9AA0A6;
        cursor: pointer;
      }

      #tabs-container {
        background-color: #1F78B4;
        width: 500px;
        height: 50px;
      }

      #display-tabs, #clear-button {
        background-color: #FFF;
        color: #4285F4;
      }

      paper-tab.iron-selected {
        color: #FFF;
        background-color: #4285F4;
        font-size: 18px;
      }

    </style>
    <div id="form-div">
        <form id="flake-form" is="iron-form" method="get" action="/p/chromium/flake-portal/flakes">
          <input type="text" name="luci_project" id="luci_project" class="hidden" value="{{luci_project}}" disabled$="{{_isValueEmpty(luci_project)}}">
          <input type="text" name="n" id="n" class="hidden" value="{{n}}" disabled$="{{_isValueEmpty(n)}}">
          <input type="text" name="cursor" id="cursor" class="hidden" value="{{cursor_in_use}}" disabled$="{{_isValueEmpty(cursor_in_use)}}">
          <input type="text" name="direction" id="direction" class="hidden" value="{{direction}}" disabled$="{{_isValueEmpty(direction)}}">
          <input type="text" name="bug_id" id="bug_id" class="hidden" value="{{bug_id}}" disabled$="{{_isValueEmpty(bug_id)}}">
          <input type="text" name="monorail_project" id="monorail_project" class="hidden" value="{{monorail_project}}" disabled$="{{_isValueEmpty(monorail_project)}}">
          <input type="text" name="flake_filter" id="flake_filter" class="hidden" value="{{ flake_filter }}" disabled$="{{_isValueEmpty(flake_filter)}}">

          <div id="tabs-container">
            <paper-tabs id="display-tabs" selected="{{selected}}">
              <paper-tab>Search By Test</paper-tab>
              <paper-tab>Search By Tags</paper-tab>
            </paper-tabs>
          </div>
           <iron-pages selected="{{selected}}">
             <div>
               <flake-filter
                id="test-filter"
                filter_type="test"
                index=0
                filter={{_getTestFilter()}}>
               </flake-filter>
             </div>
             <div id="filter-group">
               <br>
               <div id="filter-message">
                 <a on-tap="_openMessageDialog">* Press '?' for search options</a>
               </div>
            <template is="dom-if" if="{{_hasTagFilters()}}">
              <template is="dom-repeat" items="{{_getTagFilterList()}}" as="filter">
                <flake-filter
                  id="flake-filter-{{index}}"
                  filter_type="tags"
                  index={{index}}
                  filter={{filter}}
                  filter_names={{filter_names}}></flake-filter>
              </template>
            </template>
            <template is="dom-if" if="{{!_hasTagFilters()}}">
              <flake-filter
                id="flake-filter-0"
                filter_type="tags"
                index=0
                filter=''
                filter_names={{filter_names}}></flake-filter>
            </template>
          </div>
           </iron-pages>
          <div id="form-buttons">
            <paper-button id="clear-button" on-tap="_clearForm" raised>clear filters</paper-button>
            <paper-button id="submit-button" on-tap="_submitForm" raised>apply filters</paper-button>
          </div>
        </form>
    </div>
    <br>
    <div class="paging">
      <paper-button class$="previous {{_getDisabledClass(prev_cursor)}}" disabled$="{{_isValueEmpty(prev_cursor)}}" on-tap="_submitFormWithCursor">Previous</paper-button>
      <paper-button class$="next {{_getDisabledClass(cursor)}}" disabled$="{{_isValueEmpty(cursor)}}" on-tap="_submitFormWithCursor">Next</paper-button>
    </div>
    <br>
    <table width="95%">
      <tr>
        <th class="group-header flake-header" width="65%" colspan="3">Flake</th>
        <th class="group-header bug-header" width="35%" colspan="3">Bug</th>
      </tr>
      <tr>
        <th class="flake-header" width="10%">Score
        <paper-tooltip position="top" offset="0" fit-to-visible-bounds="true">Flake Score = Sum(# of impacted CLs * Weight).</paper-tooltip></th>
        <th class="flake-header" width="40%">Test Name
        <paper-tooltip position="top" offset="0" fit-to-visible-bounds="true">Name of a flaky test, or a group of parameterized tests.</paper-tooltip></th>
        <th class="flake-header" width="15%">Last Occurred
        <paper-tooltip position="top" offset="0" fit-to-visible-bounds="true">Time since last occurrence.</paper-tooltip>
        </th>
        <th class="bug-header" width="10%">Id</th>
        <th class="bug-header" width="10%">Status</th>
        <th class="bug-header" width="15%">Last Updated</th>
      </tr>
      <template is="dom-repeat" items="{{flakes}}" as="flake">
        <rank-flake-item flake={{flake}} weights={{weights}}></rank-flake-item>
      </template>
    </table>
  </template>
  <script>
    (function () {
      "use strict";

      Polymer({
        is: "rank-flakes",
        properties: {
          // A list of Flake objects to be ranked and displayed.
          flakes: {
            type: Array
          },
          weights: {
            type: Array
          },
          luci_project: {
            type: String,
            value: 'chromium'
          },
          n: {
            type: String
          },
          cursor: {
            type: String
          },
          prev_cursor: {
            type: String
          },
          bug_id: {
            type: String
          },
          monorail_project: {
            type: String
          },
          flake_filter: {
            type: String
          },
          direction: {
            type: String,
            value: ""
          },
          cursor_in_use: {
            type: String,
            value: ""
          },
          filter_names: {
            type: Array
          },
          selected: {
            type: Number,
          }
        },

        ready: function() {
          this.selected = this._getFilterTabSelected();
        },

        _getFilterTabSelected: function () {
          if (this._hasTagFilters()) {
            // There are tag filters.
            return 1;
          }
          return 0;
        },

        _hasFilter: function () {
          return Boolean(this.flake_filter);
        },

        _getFilterList: function () {
          if (this._hasFilter() && this.flake_filter.indexOf("::") > 0 ) {
            return this.flake_filter.split("@");
          }
          return [];
        },

        _getTestFilter: function () {
          let filters = this._getFilterList();
          for (let f of filters) {
            let x = f.indexOf("test::");
            if (f.indexOf("test::") >= 0) {
              return f;
            }
          }
          return '';
        },

        _hasTestFilter: function () {
          if (this._getTestFilter() != '') {
            return true;
          }
          return false;
        },

        _getTagFilterList: function () {
          if (! this._hasTestFilter()) {
            return this._getFilterList();
          }
          return [];
        },

        _hasTagFilters: function () {
          if (this._getTagFilterList().length != 0) {
            return true;
          }
          return false;
        },

        _isValueEmpty: function (value) {
          return typeof(value) == "undefined" || value == null || value == "";
        },

        _getDisabledClass: function (value) {
          if (value == "") return "disabled";
          return "";
        },

        // Event handlers.
        _openMessageDialog: function (e) {
          displayMessage(600);
        },

        _clearForm: function (e) {
          let clearButton = this.shadowRoot.querySelector('#clear-button');
          let form = clearButton.parentElement.parentElement;
          this.flake_filter = "";
          form.submit();
        },

        _submitFormWithCursor: function(e) {
          let pageButton = Polymer.dom(e).localTarget;
          if (pageButton.classList.contains('previous')) {
            this.cursor_in_use = this.prev_cursor;
            this.direction = 'previous';
          } else {
            this.cursor_in_use = this.cursor;
            this.direction = 'next';
          }

          this._submitForm(e);
        },

        _submitForm: function (e) {
          let form = this.shadowRoot.querySelector('#flake-form');

          // Filter by a specific test.
          if (this.selected == 0) {
            let test_filter = this.shadowRoot.querySelector('#test-filter');
            let filter_content = test_filter.filter;
            if (filter_content && filter_content.endsWith('::')) {
               // Incomplete input, ignore.
               filter_content = '';
             }
            this.flake_filter = filter_content;
            form.submit();
            return;
          }

          // Filter by tag(s).
          let filter_group = this.shadowRoot.querySelector('#filter-group');
          let old_filter = this.flake_filter;
          this.flake_filter = '';
          for (let filter of filter_group.querySelectorAll('flake-filter')) {
             let filter_content = filter.filter;

             if (filter_content && filter_content.endsWith('::')) {
               // Incomplete input, ignore.
               continue;
             }

             // Concatenates filters.
             if (filter_content && this.flake_filter == "") {
               this.flake_filter += filter_content;
             } else if (filter_content) {
               this.flake_filter += '@' + filter_content;}
          }
          form.submit();
        },
      });
    })();
  </script>
</dom-module>
